'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');

class CalendarController extends Controller {
  // 分页
  async index() {
    const { query, service } = this.ctx;
    let { page, size, content } = query;
    page = Number(page) || 1;
    size = Number(size) || 10;
    content = content || '';
    const where = {
      name: { [Op.like]: `%${content}%` },
    };
    const Category = await service.category.getPage(where, page, size);
    this.ctx.success(Category);
  }
  // 新增
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service.category.create(data);
    ctx.success(data);
  }

  // 修改
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递用户ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service.category.update(id, infos);
    ctx.success(id);
  }

  // 删除
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service.category.deleteById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }

  // 所有列表
  async allList() {
    const { service } = this.ctx;
    const categorys = await service.category.allList();
    this.ctx.success(categorys);
  }
}

module.exports = CalendarController;
